<?php

namespace app\api\model\wanlshop;

use app\admin\model\User;
use app\common\model\UserFinanceLog;
use think\Db;
use think\Exception;
use think\Model;

class Withdraw extends Model
{
    // 表名
    protected $name = 'withdraw';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
    ];

    public function getSettledmoneyAttr($value, $data)
    {
        return max(0, sprintf("%.2f", $data['money'] - $data['handingfee'] - $data['taxes']));
    }

    /**
     * @param $uid
     * @param $params
     * @return bool|string
     */
    public function actWithdrawHandle($uid, $params)
    {
        if (empty($params['amount']) || $params['amount'] < 0) {
            return '提现金额错误';
        }
        if (empty($params['type']) || $params['type'] != 3) {
            return '提现类型错误';
        }
        Db::startTrans();
        try {
            $user = User::find($uid);
            $actCashBackModel = new ActCashBack();
            $list = $actCashBackModel->where([
                'user_id' => $uid,
                'w_act_state' => 1,//活动提现状态 0 已冻结 1 可提现 2 已提现 3-已过期'
                'w_type' => 1,//0 换购提现 1 活动提现 2 转介绍
                'act_available_time' => ['>', time()]
            ])->select();
            if (!$list) {
                throw new Exception('活动提现数据不存在');
            }
            $total = array_sum(array_column($list, 'amount_withdrawal'));

            if ($params['amount'] > $total) {
                throw new Exception('可提现金额不足');
            }
            $actCashBackModel->where('id', 'in', array_column($list, 'id'))->update(['w_act_state' => 2]);

            UserFinanceLog::addRecord([[
                'user_id' => $uid,
                'type' => 'money',
                'flag' => 'add',
                'value' => $total,
                'before' => $user->money,
                'after' => bcadd($user->money, $total),
                'event' => 'withdraw',
                'status' => 'succeed',
            ]]);

            $user->money = bcadd($user->money, $total);
            $user->return_money = bcadd($user->return_money, $total);
            $user->save();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return true;
    }
}